package com.example.ams.controller;

import com.example.ams.dto.ClockRecordDTO;
import com.example.ams.entity.ClockRecord;
import com.example.ams.service.ClockRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 打卡记录管理控制器
 * Clock Record Controller
 */
@RestController
@RequestMapping("/api/clock-records")
@CrossOrigin(origins = "*")
public class ClockRecordController {

    @Autowired
    private ClockRecordService clockRecordService;

    /**
     * 查询打卡记录
     * GET /api/clock-records?empId=&from=&to=
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getClockRecords(
            @RequestParam(required = false) Long empId,
            @RequestParam(required = false) String from,
            @RequestParam(required = false) String to) {

        try {
            List<ClockRecordDTO> records = clockRecordService.findByConditions(empId, from, to);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", records);
            response.put("total", records.size());

            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    /**
     * 根据ID查询打卡记录
     * GET /api/clock-records/{id}
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getClockRecordById(@PathVariable Long id) {
        try {
            ClockRecordDTO record = clockRecordService.findById(id);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", record);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 404);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    /**
     * 新增打卡记录（含手工补计）
     * POST /api/clock-records
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createClockRecord(
            @Validated @RequestBody ClockRecordDTO recordDTO) {
        try {
            ClockRecordDTO created = clockRecordService.create(recordDTO);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 201);
            response.put("message", "打卡记录创建成功");
            response.put("data", created);
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    /**
     * 删除打卡记录
     * DELETE /api/clock-records/{id}
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteClockRecord(@PathVariable Long id) {
        try {
            clockRecordService.delete(id);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "打卡记录删除成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    /**
     * 批量导入打卡记录（CSV）
     * POST /api/clock-records/import
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importClockRecords(@RequestBody Map<String, String> request) {
        try {
            String csvData = request.get("csvData");
            if (csvData == null || csvData.trim().isEmpty()) {
                throw new RuntimeException("CSV数据为空");
            }

            int successCount = clockRecordService.importFromCSV(csvData);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功导入 " + successCount + " 条打卡记录");
            response.put("count", successCount);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    /**
     * 根据数据来源查询
     * GET /api/clock-records/source/{source}
     */
    @GetMapping("/source/{source}")
    public ResponseEntity<Map<String, Object>> getBySource(@PathVariable String source) {
        try {
            ClockRecord.Source sourceEnum = ClockRecord.Source.valueOf(source.toUpperCase());
            List<ClockRecordDTO> records = clockRecordService.findBySource(sourceEnum);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", records);
            response.put("total", records.size());

            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", "无效的数据来源，请使用 DEVICE 或 MANUAL");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
}

